import { reqSchedule, reqScheduleList, reqScheduleRules } from '@/api/hospital/hospitalList';
import { IResScheduleListData, IScheduleData, IScheduleRules } from '@/api/hospital/hospitalList/model/hospitalListType';
import { Card, Col, Row, Tree, TreeProps, Tag, Pagination, message, Table, Button } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

let depcode: string;
export default function HospitalSchedule() {
  const { hoscode, hosname } = useParams();
  const [schedule, setSchedule] = useState<IScheduleData[]>([]);
  const [scheduleRule, setScheduleRule] = useState<IScheduleRules[]>([]);
  const [scheduleList, setScheduleList] = useState<IResScheduleListData[]>([]);
  const [depList, setDepList] = useState<string[]>([]);
  const [depcodes, setDepcodes] = useState('');
  const [depname, setDepname] = useState('');
  const [workDate, setWorkDate] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);
  const [height, setHeight] = useState(document.documentElement.clientHeight - 64 - 44 - 48 - 36);
  const navigate = useNavigate();

  //  生命周期函数
  useEffect(() => {
    getSchedule();

    window.addEventListener('resize', resize);

    return () => {
      window.removeEventListener('resize', resize);
    };
  }, []);

  // 获取科室数据
  async function getSchedule() {
    if (hoscode) {
      const res = await reqSchedule(hoscode);
      // 给第一个分支添加不可选
      res.forEach(item => {
        item.disabled = true;
      });
      // 获取默认展开分支
      setSchedule(res);
      // 获取默认展开的 id列表
      setDepList(res.map(item => item.depcode));
      // 设置默认展示的科室
      setDepname(res[0].children[0].depname);

      // 设置默认选中的科室
      depcode = res[0].children[0].depcode;

      // 获取排班规则数据
      const workDate = await getScheduleRule();

      await getScheduleList(workDate as string);
    }
  }

  // 获取排班规则数据
  async function getScheduleRule(page = 1, pageSize = 5) {
    try {
      const res = await reqScheduleRules(page, pageSize, hoscode as string, depcode);
      // 排班列表
      setScheduleRule(res.bookingScheduleList);
      // 设置分页器的总数量
      setTotal(res.total);
      // 设置默认日期
      setWorkDate(res.bookingScheduleList[0].workDate);
      return res.bookingScheduleList[0].workDate;
    } catch (error) {
      console.log(error);
      message.error('获取排班规则数据失败');
    }
  }

  // 获取workDate排班日期的排班详细列表
  async function getScheduleList(workDate: string) {
    try {
      const res = await reqScheduleList(hoscode as string, depcode, workDate);
      setScheduleList(res);
    } catch (error) {
      console.log(error);
      message.error('获取排班详细列表失败');
    }
  }
  // 监听窗口变化
  function resize() {
    setHeight(document.documentElement.clientHeight - 64 - 44 - 48 - 36);
  }

  // 树控组件选中后触发的函数
  const onSelect: TreeProps['onSelect'] = async (selectedKeys, info: any) => {
    // 选中的id数组
    console.log(selectedKeys, 'selectedKeys');
    // 选中的信息列表
    console.log(info, 'info');
    // 修改选中的科室
    depcode = selectedKeys[0] as string;
    // 修改面包屑名字
    setDepname(info.node.depname);
    // 重新发请求获取排班规则
    const workDate = await getScheduleRule(1, pageSize);

    // 判断选择的有没有数据
    if (!workDate) {
      message.info('暂无数据');
      setScheduleRule([]);
      return;
    }
    // 获取workDate排班日期的排班详细列表
    await getScheduleList(workDate);
  };

  // 改变选择的日期
  const changeDate = (workDate: string) => {
    // 改变日期，重新发送请求获取排班
    setWorkDate(workDate);
    getScheduleList(workDate);
  };

  // 表格列
  const columns: ColumnsType<IResScheduleListData> = [
    {
      title: '序号',
      render(_, record, index) {
        return index + 1;
      },
      align: 'center',
      width: 80,
    },
    {
      title: '职称',
      dataIndex: 'title',
    },
    {
      title: '号源时间',
      dataIndex: 'workDate',
    },
    {
      title: '可预约数',
      dataIndex: 'availableNumber',
    },
    {
      title: '剩余预约数',
      dataIndex: 'reservedNumber',
    },
    {
      title: '挂号费(元)',
      dataIndex: 'amount',
    },
    {
      title: '擅长技能',
      dataIndex: 'skill',
    },
  ];
  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      {/* 行,gutter表示两个列直接相隔的距离 */}
      <Row gutter={20}>
        {/* 列 */}
        <Col span={5}>
          <div style={{ border: '1px solid #ccc', height, overflow: 'scroll' }}>
            <Tree
              // 选中时触发的函数
              onSelect={onSelect}
              treeData={schedule as any} //渲染的数据
              expandedKeys={depList} //默认展开的节点 值是一个id数组
              // 数控组件默认用title渲染文本，用key渲染节点的id，配置fieldNames就可以自定义渲染文本的属性和作为id的属性
              fieldNames={{
                title: 'depname',
                key: 'depcode',
              }}></Tree>
          </div>
        </Col>
        <Col span={19}>
          {scheduleRule.map(item => {
            return (
              <Tag
                onClick={() => {
                  changeDate(item.workDate);
                }}
                color={item.workDate == workDate ? 'success' : ''}
                key={item.workDate}>
                {item.workDate} {item.dayOfWeek}
                <div>
                  {item.availableNumber} / {item.reservedNumber}
                </div>
              </Tag>
            );
          })}

          <Pagination
            style={{ marginTop: 20, marginBottom: 20 }}
            pageSize={pageSize}
            total={total}
            current={page}
            showSizeChanger
            pageSizeOptions={[2, 5, 10]}
            onChange={(page, pageSize) => {
              setPage(page);
              setPageSize(pageSize);
              getScheduleRule(page, pageSize);
            }}></Pagination>

          <Table bordered dataSource={scheduleList} columns={columns} rowKey={'id'} pagination={false}></Table>

          <Button
            style={{ marginTop: 20 }}
            onClick={() => {
              navigate(-1);
            }}>
            {' '}
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  );
}
